# 登录接口

import os
import requests
import yaml
import logging
from typing import Optional, Any, Dict, List
from yaml import FullLoader

logger = logging.getLogger(__name__)
if not logger.hasHandlers():
    handler = logging.StreamHandler()
    formatter = logging.Formatter('[%(asctime)s] %(levelname)s %(name)s: %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    logger.setLevel(logging.INFO)


def find_yaml_file(possible_paths: List[str] = None) -> Optional[str]:
    """
    查找 YAML 文件，支持多路径查找。
    """
    if possible_paths is None:
        possible_paths = [
            'data/testcases.yaml',
            'testcases.yaml',
            os.path.join(os.path.dirname(__file__), '../data/testcases.yaml'),
        ]

    for path in possible_paths:
        abs_path = os.path.abspath(path)
        if os.path.exists(abs_path):
            return abs_path
    logger.warning("未找到 YAML 文件，查找路径: %s", possible_paths)
    return None


def read_yaml_file(file_path: str) -> Any:
    """
    读取 YAML 文件内容。
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            # 使用 FullLoader 更安全地加载 YAML
            return yaml.load(f, Loader=FullLoader)
    except Exception as e:
        logger.error(f"读取 YAML 文件失败: {file_path}, 错误: {e}")
        return None


def send_request_from_case(case: Dict[str, Any]) -> Dict[str, Any]:
    """
    根据单条用例发送请求，支持 method, url, params, data, json, headers。
    """
    method = case.get('method', 'get').lower()
    url = case.get('url')
    params = case.get('params')
    data = case.get('data')
    json_data = case.get('json')
    headers = case.get('headers')
    result = {'testcase': case}

    if not url:
        result['error'] = '缺少 url 字段'
        return result

    try:
        resp = requests.request(
            method,
            url,
            params=params,
            data=data,
            json=json_data,
            headers=headers
        )

        content_type = resp.headers.get('Content-Type', '')
        if 'application/json' in content_type:
            body = resp.json()
        else:
            body = resp.text

        result.update({
            'status_code': resp.status_code,
            'response': body
        })
    except Exception as e:
        result['error'] = str(e)
    return result


def run_yaml_requests(yaml_path: Optional[str] = None) -> List[Dict[str, Any]]:
    """
    读取 YAML 并批量发送请求，返回结果列表。
    """
    if not yaml_path:
        yaml_path = find_yaml_file()

    if not yaml_path:
        logger.error("未找到 YAML 文件，无法执行用例")
        return []

    data = read_yaml_file(yaml_path)

    if not data:
        logger.error("YAML 文件内容为空或解析失败")
        return []

    if not isinstance(data, list):
        logger.error("YAML 文件内容应为测试用例列表")
        return []

    logger.info(f"读取到 {len(data)} 条测试用例")
    results = [send_request_from_case(case) for case in data]
    return results


if __name__ == "__main__":
    # 添加调试信息
    print("开始执行测试用例...")
    results = run_yaml_requests()

    if not results:
        print("没有获取到任何测试结果")
    else:
        for i, res in enumerate(results, 1):
            print(f"\n=== 测试用例 {i} ===")
            print(res)